﻿import sys
import os
import json
from urllib2 import HTTPError, URLError
from datetime import date
from calendar import Calendar

import ParseHelpUtils
import WebUtils
import Cache
import BirthInfo
from BirthInfoTemplate import BirthInfoTemplate

#===================================================================
def add_birth_event(countries, event, birth_events):

    for country in countries:
        if country:
            try:
                birth_events[country].append(event)
            except KeyError:
                birth_events[country] = [event]

    return birth_events

#===================================================================

# Get a birth event as parameter.
# Example: " 1858 – Jagdish Chandra Bose, Indian physicist (d. 1937)".
# Guess nationality from this event. From nationality, get the country.
# Group events based on country.

def associate_countries_with_births(births):
    nationalities = list()
    countries = list()
    birth_events = {}

    births_coountries = {}

    for birth in births:
        nationalities = ParseHelpUtils.guess_nationalities(birth)
        countries = [ParseHelpUtils.lookup_country(nationality) for nationality in nationalities]
        add_birth_event(countries, birth, birth_events)

    for country, birth_event in birth_events.iteritems():
        births_countries[country] = '\n'.join(birth_event)

    return births_countries

#===================================================================

# To make the events show up as a bulleted list in the map info window
def decorate_events(events):
    if '\n' in events:
        events = "<ul><li>" + events.replace("\n", "</li><li>") + "</li></ul>"

    return events

#===================================================================

# Transform BirthInfo to a BirthInfoTemplate. BirthInfoTemplate will be used
# to generate the html template.
def transform_birth_infos(birth_infos):
    birth_info_templates = []

    for birth_info in birth_infos:
        for location, latlong in birth_info.location.iteritems():
            birth_events_with_html = json.dumps(decorate_events(birth_info.birth_events))
            
            birth_info_templates.append(BirthInfoTemplate(birth_events_with_html.encode("utf-8"), 
                					location.encode("utf-8"), 
							latlong['lat'],
							latlong['lng']))

    return birth_info_templates

#===================================================================

def get_coordinates(country, loc_cache, nohits_cache):
   
    coordinates = dict()
    updates = dict()
    nohits = dict()
    
    if country != "":
        lat_long = loc_cache.get_item(country)
            
        if lat_long:
            coordinates[country] = lat_long

            return coordinates, updates, nohits

        if nohits_cache.get_item(country):
            return coordinates, updates, nohits

        lat_long = WebUtils.lookup_google(country)
        if lat_long:
            updates[country] = lat_long
        else:
            nohits[country] = 'P' # Dummy "value"

    return coordinates, updates, nohits

#===================================================================

def births_of_the_day(day_of_year):

    wikipedia_base_url = "http://en.wikipedia.org/wiki/"
    
    wikipedia_url = "{0}{1}".format(wikipedia_base_url, day_of_year)

    if not day_of_year:
        day_of_year = date.today().strftime('%B_%d')
        
    births_countries = dict()

    birth_infos = []

    APP_ROOT = os.path.dirname(os.path.realpath(__file__))
    CACHE_PATH = os.path.join(APP_ROOT, '../cache')
    HITS_CACHE = os.path.join(CACHE_PATH, 'places.txt')
    NOHITS_CACHE = os.path.join(CACHE_PATH, 'nohits.txt')

    try:
        print "Loading Cache from", HITS_CACHE
        loc_cache = Cache.Cache(HITS_CACHE)
        loc_cache.load_cache()
    
        print "Loading No-Hits Cache from", NOHITS_CACHE
        nohits_cache = Cache.Cache(NOHITS_CACHE)
        nohits_cache.load_cache()
    
    except (IOError) as (strerror):
        print "Error loading Cache: {0}".format(strerror)
        return None

    try:
        html_content = WebUtils.get_content(wikipedia_url)
    
    except (HTTPError) as error:
        print "Error fetching content from wikipedia: {0}".format(str(error))
        if error.code == 404:
            return error.code

        return None

    except (URLError) as error:
        print "Error fetching content from wikipedia: {0}".format(str(error))
        return None
    
    births = WebUtils.extract_births(html_content)

    births_countries = associate_countries_with_births(births)
        
    for country, events in births_countries.iteritems():
        if country:
            coordinates, updates, nohits = get_coordinates(country, loc_cache, nohits_cache)
            birth_info = BirthInfo.BirthInfo(events, coordinates)

            birth_infos.append(birth_info)

    try:
        if loc_cache.write_cache_to_disk() == False:
            print "Error updating Cache"
        
        if nohits_cache.write_cache_to_disk() == False:
            print "Error updating No-Hits Cache"
        
    except IOError as (errno, strerror):
        print "Error Updating Cache: errno: {0}, {1}".format(errno, strerror)

    return birth_infos
        
#===================================================================

if __name__ == "__main__":
    print "Main Called"
    if len(sys.argv) == 1:
        births_of_the_day(date.today().strftime('%B_%d'))
    else:
        births_of_the_day(sys.argv[1])
